package com.icongyou.enterprise.course_detail.service.impl;

import com.icongyou.enterprise.course_detail.entity.AssignmentEntity;
import com.icongyou.enterprise.course_detail.entity.AssignmentRankEntity;
import com.icongyou.enterprise.course_detail.entity.vo.AssignmentCardVO;
import com.icongyou.enterprise.course_detail.mapper.CourseDetailMapper;
import com.icongyou.enterprise.data_aggregation.entity.*;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_marking.service.HighPotentialSubmissionService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class CourseDetailServiceImplTest {

    @InjectMocks
    private CourseDetailServiceImpl service;

    @Mock
    private CourseDetailMapper courseDetailMapper;

    @Mock
    private DataAggregationService dataAggregationService;

    @Mock
    private HighPotentialSubmissionService highPotentialSubmissionService;

    @Test
    public void testGetCourseDetail_personalAssignment_withGrade() {
        String studentId = "660e8400-e29b-41d4-a716-446655440101";
        String courseId = "aa0e8400-e29b-41d4-a716-446655440501";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Course 1");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Alice");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("92.5"));
        progress.setRanking(3);

        // Assignment
        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("ee0e8400-e29b-41d4-a716-446655440901");
        assignment.setAssignmentName("第一周个人作业：环境搭建");
        assignment.setAssignmentType(0); // personal
        assignment.setStartTime(LocalDateTime.now().minusDays(5));

        // Submission by the student (personal task => no contributionRate)
        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s1");
        submission.setAssignmentId("ee0e8400-e29b-41d4-a716-446655440901");
        submission.setStudentId(studentId);
        submission.setSubmissionTime(LocalDateTime.now().minusDays(1));
        submission.setIsLate(0);
        submission.setLikeCount(2);
        submission.setFavoriteCount(1);

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("80"));
        grade.setTextComment("Well done");

        AssignmentRankEntity rankEntity = new AssignmentRankEntity();
        rankEntity.setAssignmentId("ee0e8400-e29b-41d4-a716-446655440901");
        rankEntity.setStudentId(studentId);
        rankEntity.setRank(5);

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s1")).thenReturn(Collections.singletonList(grade));

        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId)).thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("ee0e8400-e29b-41d4-a716-446655440901", studentId)).thenReturn(rankEntity);
        when(courseDetailMapper.getAssignmentRankings("ee0e8400-e29b-41d4-a716-446655440901")).thenReturn(Collections.singletonList(rankEntity));

        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s1")).thenReturn(true);

        // assigned scores: none
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        assertEquals(courseId, vo.getCourseId());
        assertEquals(studentId, vo.getStudentId());
        assertEquals(3, vo.getCourseRank());

        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertNotNull(assignments);
        assertEquals(1, assignments.size());

        AssignmentCardVO card = assignments.get(0);
        assertEquals("ee0e8400-e29b-41d4-a716-446655440901", card.getAssignmentId());
        assertEquals(0, new BigDecimal("80.00").compareTo(card.getScore()));
        assertEquals(0, new BigDecimal("100").compareTo(card.getContributionRate()));
        assertEquals("Well done", card.getTeacherComment());
        assertEquals(5, card.getAssignmentRank());
    }

    @Test
    public void testGetCourseDetail_teamAssignment_withContribution() {
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Team Project Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Bob");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("85.0"));
        progress.setRanking(5);

        // Team Assignment
        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a2");
        assignment.setAssignmentName("Team Project");
        assignment.setAssignmentType(1); // team
        assignment.setStartTime(LocalDateTime.now().minusDays(10));

        // Team submission with contribution rates
        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s2");
        submission.setAssignmentId("a2");
        submission.setStudentId("stu2"); // team leader
        submission.setTeamId("team1");
        submission.setSubmissionTime(LocalDateTime.now().minusDays(2));
        submission.setIsLate(0);
        
        // Contribution rates
        List<SubmissionEntity.ContributionItem> contributions = new ArrayList<>();
        SubmissionEntity.ContributionItem item1 = new SubmissionEntity.ContributionItem();
        item1.setStudentId(studentId);
        item1.setRate(new BigDecimal("35"));
        contributions.add(item1);
        
        SubmissionEntity.ContributionItem item2 = new SubmissionEntity.ContributionItem();
        item2.setStudentId("stu2");
        item2.setRate(new BigDecimal("40"));
        contributions.add(item2);
        
        SubmissionEntity.ContributionItem item3 = new SubmissionEntity.ContributionItem();
        item3.setStudentId("stu3");
        item3.setRate(new BigDecimal("25"));
        contributions.add(item3);
        
        submission.setContributionRate(contributions);

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("90"));
        grade.setTextComment("Excellent teamwork");

        AssignmentRankEntity rankEntity = new AssignmentRankEntity();
        rankEntity.setAssignmentId("a2");
        rankEntity.setStudentId(studentId);
        rankEntity.setRank(2);

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s2")).thenReturn(Collections.singletonList(grade));
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());

        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId)).thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a2", studentId)).thenReturn(rankEntity);
        when(courseDetailMapper.getAssignmentRankings("a2")).thenReturn(Collections.singletonList(rankEntity));

        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s2")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());

        AssignmentCardVO card = assignments.get(0);
        assertEquals("a2", card.getAssignmentId());
        assertEquals(0, new BigDecimal("35").compareTo(card.getContributionRate()));
        // Score should be 90 * 35% = 31.50
        assertEquals(0, new BigDecimal("31.50").compareTo(card.getScore()));
        assertEquals("Excellent teamwork", card.getTeacherComment());
        assertEquals(2, card.getAssignmentRank());
    }

    @Test
    public void testGetCourseDetail_noSubmission_withAssignedScore() {
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Course with partial data");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Charlie");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("70.0"));
        progress.setRanking(10);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a3");
        assignment.setAssignmentName("Late Assignment");
        assignment.setAssignmentType(0);
        assignment.setStartTime(LocalDateTime.now().minusDays(3));

        // Student has assigned score but no submission
        AssignmentStudentEntity assignedScore = new AssignmentStudentEntity();
        assignedScore.setAssignmentId("a3");
        assignedScore.setStudentId(studentId);
        assignedScore.setAssignedScore(new BigDecimal("60"));

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(new ArrayList<>());
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId))
            .thenReturn(Collections.singletonList(assignedScore));

        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a3", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a3")).thenReturn(new ArrayList<>());

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());

        AssignmentCardVO card = assignments.get(0);
        assertEquals("a3", card.getAssignmentId());
        assertEquals(0, new BigDecimal("60").compareTo(card.getScore()));
        assertNull(card.getSubmissionTime());
        assertNull(card.getAssignmentRank());
    }

    @Test
    public void testGetCourseDetail_lateSubmission() {
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Course 1");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Diana");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("75.0"));
        progress.setRanking(8);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a4");
        assignment.setAssignmentName("Late Homework");
        assignment.setAssignmentType(0);
        assignment.setStartTime(LocalDateTime.now().minusDays(7));

        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s4");
        submission.setAssignmentId("a4");
        submission.setStudentId(studentId);
        submission.setSubmissionTime(LocalDateTime.now().minusDays(1));
        submission.setIsLate(1); // Late submission

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("70"));
        grade.setTextComment("Late but acceptable");

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s4")).thenReturn(Collections.singletonList(grade));
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());

        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a4", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a4")).thenReturn(new ArrayList<>());

        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s4")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());

        AssignmentCardVO card = assignments.get(0);
        assertTrue(card.getIsLate());
        assertEquals(0, new BigDecimal("70.00").compareTo(card.getScore()));
    }

    @Test
    public void testGetCourseDetail_multipleAssignments_rankTrend() {
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Multi Assignment Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Eve");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("88.0"));
        progress.setRanking(4);

        // Create 3 assignments
        List<AssignmentEntity> assignments = new ArrayList<>();
        List<SubmissionEntity> submissions = new ArrayList<>();
        List<AssignmentRankEntity> ranks = new ArrayList<>();

        for (int i = 1; i <= 3; i++) {
            AssignmentEntity assignment = new AssignmentEntity();
            assignment.setAssignmentId("a" + i);
            assignment.setAssignmentName("Assignment " + i);
            assignment.setAssignmentType(0);
            assignment.setStartTime(LocalDateTime.now().minusDays(10 - i));
            assignments.add(assignment);

            SubmissionEntity submission = new SubmissionEntity();
            submission.setSubmissionId("s" + i);
            submission.setAssignmentId("a" + i);
            submission.setStudentId(studentId);
            submission.setSubmissionTime(LocalDateTime.now().minusDays(9 - i));
            submission.setIsLate(0);
            submissions.add(submission);

            AssignmentRankEntity rank = new AssignmentRankEntity();
            rank.setAssignmentId("a" + i);
            rank.setStudentId(studentId);
            rank.setRank(5 - i); // Improving rank: 4, 3, 2
            ranks.add(rank);

            GradeEntity grade = new GradeEntity();
            grade.setFinalScore(new BigDecimal(85 + i * 2));
            grade.setTextComment("Good work " + i);
            when(dataAggregationService.getStudentGrade("s" + i))
                .thenReturn(Collections.singletonList(grade));

            when(courseDetailMapper.getStudentAssignmentRank("a" + i, studentId)).thenReturn(rank);
            when(courseDetailMapper.getAssignmentRankings("a" + i))
                .thenReturn(Collections.singletonList(rank));
            when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s" + i)).thenReturn(false);
        }

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(submissions);
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId)).thenReturn(assignments);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        assertEquals(3, vo.getAssignments().size());
        
        // Check rank trend
        assertNotNull(vo.getRankTrend());
        assertEquals(3, vo.getRankTrend().size());
        assertEquals(4, vo.getRankTrend().get(0).getRank());
        assertEquals(3, vo.getRankTrend().get(1).getRank());
        assertEquals(2, vo.getRankTrend().get(2).getRank());
    }

    @Test
    public void testGetCourseDetail_teamAssignment_emptyContributionList() {
        // 测试团队任务但贡献度列表为空的情况
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Team Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Test Student");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("80.0"));
        progress.setRanking(6);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a_team");
        assignment.setAssignmentName("Team Project");
        assignment.setAssignmentType(1); // team
        assignment.setStartTime(LocalDateTime.now().minusDays(5));

        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s_team");
        submission.setAssignmentId("a_team");
        submission.setStudentId("other_student");
        submission.setTeamId("team1");
        submission.setSubmissionTime(LocalDateTime.now().minusDays(2));
        submission.setIsLate(0);
        submission.setContributionRate(new ArrayList<>()); // 空列表

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("85"));

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s_team")).thenReturn(Collections.singletonList(grade));
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a_team", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a_team")).thenReturn(new ArrayList<>());
        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s_team")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());
        // 团队任务没有贡献度时应为0，但可能返回null
        BigDecimal contributionRate = assignments.get(0).getContributionRate();
        if (contributionRate != null) {
            assertEquals(0, new BigDecimal("0").compareTo(contributionRate));
        } else {
            // 如果为null也是合理的
            assertTrue(true);
        }
    }

    @Test
    public void testGetCourseDetail_personalAssignment_withContributionRateButShouldBe100() {
        // 测试个人任务的贡献度处理（应该是100%）
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Personal Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Test Student");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("90.0"));
        progress.setRanking(2);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a_personal");
        assignment.setAssignmentName("Personal Assignment");
        assignment.setAssignmentType(0); // personal
        assignment.setStartTime(LocalDateTime.now().minusDays(3));

        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s_personal");
        submission.setAssignmentId("a_personal");
        submission.setStudentId(studentId);
        submission.setSubmissionTime(LocalDateTime.now().minusDays(1));
        submission.setIsLate(0);
        submission.setContributionRate(null); // 个人任务通常没有贡献度

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("95"));

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s_personal")).thenReturn(Collections.singletonList(grade));
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a_personal", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a_personal")).thenReturn(new ArrayList<>());
        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s_personal")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());
        // 个人任务贡献度应为100%
        assertEquals(0, new BigDecimal("100").compareTo(assignments.get(0).getContributionRate()));
    }

    @Test
    public void testGetCourseDetail_teamAssignment_withAssignedScoreAndContribution() {
        // 测试团队任务有assignedScore和贡献度的情况
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Team Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Team Member");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("88.0"));
        progress.setRanking(3);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a_team_assigned");
        assignment.setAssignmentName("Team Project with Assigned Score");
        assignment.setAssignmentType(1); // team
        assignment.setStartTime(LocalDateTime.now().minusDays(7));

        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s_team_assigned");
        submission.setAssignmentId("a_team_assigned");
        submission.setStudentId("team_leader");
        submission.setTeamId("team1");
        submission.setSubmissionTime(LocalDateTime.now().minusDays(3));
        submission.setIsLate(0);

        List<SubmissionEntity.ContributionItem> contributions = new ArrayList<>();
        SubmissionEntity.ContributionItem item1 = new SubmissionEntity.ContributionItem();
        item1.setStudentId(studentId);
        item1.setRate(new BigDecimal("50"));
        contributions.add(item1);

        SubmissionEntity.ContributionItem item2 = new SubmissionEntity.ContributionItem();
        item2.setStudentId("team_leader");
        item2.setRate(new BigDecimal("50"));
        contributions.add(item2);

        submission.setContributionRate(contributions);

        // 没有grade，但有assignedScore
        AssignmentStudentEntity assignedScore = new AssignmentStudentEntity();
        assignedScore.setAssignmentId("a_team_assigned");
        assignedScore.setStudentId(studentId);
        assignedScore.setAssignedScore(new BigDecimal("80"));

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s_team_assigned")).thenReturn(new ArrayList<>()); // 没有grade
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId))
            .thenReturn(Collections.singletonList(assignedScore));
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a_team_assigned", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a_team_assigned")).thenReturn(new ArrayList<>());
        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s_team_assigned")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());
        AssignmentCardVO card = assignments.get(0);
        // 80 * 50% = 40
        assertEquals(0, new BigDecimal("40").compareTo(card.getScore()));
        assertEquals(0, new BigDecimal("50").compareTo(card.getContributionRate()));
    }

    @Test
    public void testGetCourseDetail_multipleSubmissionsSelectLatest() {
        // 测试多个提交记录时选择最新的
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Student");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("85.0"));
        progress.setRanking(5);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a_multi");
        assignment.setAssignmentName("Assignment");
        assignment.setAssignmentType(0);
        assignment.setStartTime(LocalDateTime.now().minusDays(10));

        // 多个提交，应该选择最新的
        List<SubmissionEntity> submissions = new ArrayList<>();

        SubmissionEntity oldSubmission = new SubmissionEntity();
        oldSubmission.setSubmissionId("s_old");
        oldSubmission.setAssignmentId("a_multi");
        oldSubmission.setStudentId(studentId);
        oldSubmission.setSubmissionTime(LocalDateTime.now().minusDays(5));
        oldSubmission.setIsLate(0);
        submissions.add(oldSubmission);

        SubmissionEntity newSubmission = new SubmissionEntity();
        newSubmission.setSubmissionId("s_new");
        newSubmission.setAssignmentId("a_multi");
        newSubmission.setStudentId(studentId);
        newSubmission.setSubmissionTime(LocalDateTime.now().minusDays(1)); // 最新的
        newSubmission.setIsLate(0);
        submissions.add(newSubmission);

        GradeEntity newGrade = new GradeEntity();
        newGrade.setFinalScore(new BigDecimal("92"));
        newGrade.setTextComment("Improved version");

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(submissions);
        when(dataAggregationService.getStudentGrade("s_new")).thenReturn(Collections.singletonList(newGrade));
        when(dataAggregationService.getStudentGrade("s_old")).thenReturn(new ArrayList<>()); // 旧提交没有成绩
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a_multi", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a_multi")).thenReturn(new ArrayList<>());
        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s_new")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());
        // 应该使用最新提交的成绩
        assertEquals(0, new BigDecimal("92.00").compareTo(assignments.get(0).getScore()));
        assertEquals("Improved version", assignments.get(0).getTeacherComment());
    }

    @Test
    public void testGetCourseDetail_noAssignments() {
        // 测试没有任务的情况
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Empty Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Student");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("0"));
        progress.setRanking(null);

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId)).thenReturn(new ArrayList<>());
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId)).thenReturn(new ArrayList<>());

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        assertNotNull(vo.getAssignments());
        assertEquals(0, vo.getAssignments().size());
        assertNotNull(vo.getRankTrend());
        assertEquals(0, vo.getRankTrend().size());
    }

    @Test
    public void testGetCourseDetail_teamAssignment_studentNotInContributionList() {
        // 测试团队任务，但当前学生不在贡献度列表中
        String studentId = "stu1";
        String courseId = "c1";

        CourseEntity course = new CourseEntity();
        course.setCourseId(courseId);
        course.setCourseName("Team Course");

        UserEntity student = new UserEntity();
        student.setId(studentId);
        student.setRealName("Not In Team");

        CourseProgressEntity progress = new CourseProgressEntity();
        progress.setTotalScore(new BigDecimal("60.0"));
        progress.setRanking(15);

        AssignmentEntity assignment = new AssignmentEntity();
        assignment.setAssignmentId("a_team_no_member");
        assignment.setAssignmentName("Team Project");
        assignment.setAssignmentType(1); // team
        assignment.setStartTime(LocalDateTime.now().minusDays(5));

        SubmissionEntity submission = new SubmissionEntity();
        submission.setSubmissionId("s_team_no_member");
        submission.setAssignmentId("a_team_no_member");
        submission.setStudentId("other_leader");
        submission.setTeamId("team_other");
        submission.setSubmissionTime(LocalDateTime.now().minusDays(2));
        submission.setIsLate(0);

        // 贡献度列表中不包含当前学生
        List<SubmissionEntity.ContributionItem> contributions = new ArrayList<>();
        SubmissionEntity.ContributionItem item1 = new SubmissionEntity.ContributionItem();
        item1.setStudentId("other_member1");
        item1.setRate(new BigDecimal("60"));
        contributions.add(item1);

        SubmissionEntity.ContributionItem item2 = new SubmissionEntity.ContributionItem();
        item2.setStudentId("other_member2");
        item2.setRate(new BigDecimal("40"));
        contributions.add(item2);

        submission.setContributionRate(contributions);

        GradeEntity grade = new GradeEntity();
        grade.setFinalScore(new BigDecimal("90"));

        when(dataAggregationService.getCourseById(courseId)).thenReturn(course);
        when(dataAggregationService.getStudentById(studentId)).thenReturn(student);
        when(dataAggregationService.getStudentCourseProgress(studentId, courseId)).thenReturn(progress);
        when(dataAggregationService.getStudentSubmissionsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(submission));
        when(dataAggregationService.getStudentGrade("s_team_no_member")).thenReturn(Collections.singletonList(grade));
        when(dataAggregationService.getStudentAssignmentScore(studentId, courseId)).thenReturn(new ArrayList<>());
        when(courseDetailMapper.getStudentAssignmentsByCourse(studentId, courseId))
            .thenReturn(Collections.singletonList(assignment));
        when(courseDetailMapper.getStudentAssignmentRank("a_team_no_member", studentId)).thenReturn(null);
        when(courseDetailMapper.getAssignmentRankings("a_team_no_member")).thenReturn(new ArrayList<>());
        when(highPotentialSubmissionService.isSubmissionMarked(studentId, "s_team_no_member")).thenReturn(false);

        com.icongyou.enterprise.course_detail.entity.vo.CourseDetailVO vo = service.getCourseDetail(studentId, courseId);

        assertNotNull(vo);
        List<AssignmentCardVO> assignments = vo.getAssignments();
        assertEquals(1, assignments.size());
        // 团队任务但学生不在贡献度列表中，贡献度应为0或null
        BigDecimal contributionRate = assignments.get(0).getContributionRate();
        if (contributionRate != null) {
            assertEquals(0, new BigDecimal("0").compareTo(contributionRate));
        }
    }
}
